package com.fwmagic.dynamic_rule.service.impl;

import com.fwmagic.dynamic_rule.bean.RuleAtomicParam;
import com.fwmagic.dynamic_rule.bean.RuleParam;
import com.fwmagic.dynamic_rule.service.UserActionSequenceQueryService;
import com.fwmagic.dynamic_rule.utils.ConnectionUtils;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

@Slf4j
public class UserActionSequenceQueryServiceClickHouseImpl implements UserActionSequenceQueryService {

    private static Connection connection;

    static {
        try {
            connection = ConnectionUtils.getClickHouseConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean queryActionSequence(String deviceId, RuleParam ruleParam) throws Exception {
        //规则中需要的步骤数
        int totalStep = ruleParam.getUserActionSequenceParam().size();

        RuleAtomicParam atomicParam = ruleParam.getUserActionSequenceParam().get(0);
        //次序规则的sql
        String sql = ruleParam.getActionSequenceQuerySql();
        //替换deviceId
//        sql = sql.replaceAll("\\$\\{deviceId\\}", deviceId);
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1, deviceId);
        ps.setLong(2, atomicParam.getRangeStart());
        ps.setLong(3, atomicParam.getRangeEnd());
        //查询ClickHouse
        long s = System.currentTimeMillis();
//        Statement stat = connection.createStatement();
        log.info("clickhouse seqence sql:{}",sql);
        ResultSet rs = ps.executeQuery();
        long e = System.currentTimeMillis();
        log.info("规则:{},用户:{},行为序列查询ClickHouse耗时:{} ms", ruleParam.getRuleId(), deviceId, (e - s));
        //deviceId  isMatch3    isMatch2    isMatch1
        //00000011      1           1           1
        //00000011      0           0           1
        int maxStep = 0;
        while (rs.next()) {
            for (int i = 2; i < totalStep + 2; i++) {
                int isMatch = rs.getInt(i);
                maxStep += isMatch;
            }
        }
        //设置实际匹配到的步骤
        ruleParam.setUserActionSequenceQueriedMaxStep(ruleParam.getUserActionSequenceQueriedMaxStep() + maxStep);
        return ruleParam.getUserActionSequenceQueriedMaxStep() >= totalStep;
    }
}
